package com.red.controller.user;

import com.red.constant.JwtClaimsConstant;
import com.red.context.BaseContext;
import com.red.dto.UserDto;
import com.red.dto.UserLoginDTO;
import com.red.entity.Users;
import com.red.properties.JwtProperties;
import com.red.result.PageResult;
import com.red.result.Result;
import com.red.service.UserService;
import com.red.utils.JwtUtil;
import com.red.vo.UserLoginVO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * author
 */
@RestController
@RequestMapping("/user/user")
@ApiModel(value = "用户api")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiModelProperty("用户登录")
    public Result<UserLoginVO> wxLogin(@RequestBody UserLoginDTO userLoginDTO){
        log.info("code,{}",userLoginDTO);
        //判断是否传递登录信息
        if (userLoginDTO==null){
            return Result.success(null);
        }
        Users users = userService.wxLogin(userLoginDTO);

        //生成JWT令牌
        HashMap<String , Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, users.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);

        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setOpenid(users.getOpenid());
        userLoginVO.setToken(token);
        userLoginVO.setId(users.getId());
        return Result.success(userLoginVO);
    }

    /**
     * 信息修改
     * @param userDto
     * @return
     */
    @PostMapping("/update")
    public Result updateUser(UserDto userDto){
        log.info("修改信息：{}",userDto);
        userService.updateUser(userDto);
        return Result.success();
    }

    /**
     * 回显个人信息
     * @return
     */
    @GetMapping
    public Result selectById(){
        Users byId = userService.getById(BaseContext.getCurrentId());
        return Result.success(byId);
    }
}
